<template>
  <el-dialog v-model="dialogVisible" center width="70%"  :append-to-body = "true" :close-on-click-modal="false" :before-close="handleClose" @close="onClose" style="background-color: #f5f6f8;box-sizing: border-box">
    <div class="flex justify-content-center align-center" style="margin-top: 20px">
        <div class="flex-auto"></div>
        <div class="flex-auto create-activity-title" style="text-align: center;font-size: 22px;color: #333333;font-weight: bolder;">{{!!activityId?'编辑组织活动':'新建组织活动'}}</div>
        <div class="flex-auto"></div>
    </div>
    <el-form :model="formData" label-width="100px" :rules="rules" ref="formRef" label-position="top">
      <!-- 上板块  -->
      <div style="margin-top: 20px" class="flex justify-content-space-between">
      <!-- 左边板块 -->
      <div class="flex-auto" style="background-color: #ffffff;padding: 20px;margin-right: 10px">
          <div style="width: 100%;border-bottom: 1px solid #dedcdc;padding:0 0 10px 0;margin: 0 0 20px 0;font-size: 18px;color: #3d3838;font-weight: bolder">基本信息</div>
          <div class="list">
            <el-form-item label="活动类型" prop="activityTypeId">
              <el-select v-model="formData.activityTypeId" placeholder="请选择活动类型" style="width: 100%">
                <el-option v-for="(item,index) in activitySelectList.activityTypeList" :label="item.activityTypeName" :value="item.id" :key="index" />
              </el-select>
            </el-form-item>
            <el-form-item label="活动主题" prop="activityName">
              <el-input v-model="formData.activityName" placeholder="请输入活动主题" />
            </el-form-item>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="activityStartTime" >
                  <el-date-picker v-model="formData.activityStartTime" type="datetime" style="width: 100%"   value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" placeholder="选择开始时间" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="结束时间" prop="activityEndTime">
                  <el-date-picker v-model="formData.activityEndTime" type="datetime" style="width: 100%"   value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" placeholder="选择结束时间" />
                </el-form-item>
              </el-col>

            </el-row>
            <el-form-item label="活动地点" prop="activityAddress">
              <el-input v-model="formData.activityAddress" placeholder="请输入活动地点">
                <template #append>
                  <el-icon><LocationFilled /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="活动内容" prop="activitySummary">
              <el-input v-model="formData.activitySummary" type="textarea" :rows="3" placeholder="请输入活动内容..." style="width: 100%"/>
            </el-form-item>
          </div>
      </div>
      <!-- 右边板块 -->
      <div class="flex-auto" style="background-color: #ffffff;padding: 20px;margin-left: 10px">
        <div style="width: 100%;border-bottom: 1px solid #dedcdc;padding:0 0 10px 0;margin: 0 0 20px 0;font-size: 18px;color: #3d3838;font-weight: bolder">参与人员</div>

        <el-form-item label="活动责任人" prop="userId">
          <el-select filterable v-model="formData.userId" placeholder="请选择责任人" style="width: 100%">
            <el-option v-for="(item,index) in activitySelectList.partyMemberList" :label="item.pbUserName" :value="item.id" :key="index" />
          </el-select>
        </el-form-item>

        <div class="flex">
         <div class="count-control flex-auto" style="background-color: #f3f3f6;border-radius: 10px;padding: 10px 20px;">

         <div class="flex align-center">
           <div style="margin-right: 20px">计划参与人数</div>
           <el-input-number  style="height: 35px" v-model="formData.countUserNum" :step="1" />
<!--           <el-button type="primary" style="height: 35px;margin-left: 10px">保存</el-button>-->
         </div>
       </div>
<!--          &lt;!&ndash;  签到人数  &ndash;&gt;-->
<!--         <div class="count-control flex-auto" style="margin: 0 20px;background-color: #f3f3f6;border-radius: 10px;padding: 10px 20px;">-->
<!--           <div style="padding-bottom: 10px;" class="flex align-center">-->
<!--             <el-icon style="font-size: 18px"><Avatar /></el-icon>-->
<!--             <span style="padding-left: 10px">签到人数</span>-->
<!--           </div>-->
<!--           <div style="font-size: 26px; color: #00C94F">0</div>-->
<!--         </div>-->
<!--          &lt;!&ndash;  请假人数  &ndash;&gt;-->
<!--          <div class="count-control flex-auto" style="background-color: #f3f3f6;border-radius: 10px;padding: 10px 20px;">-->
<!--            <div style="padding-bottom: 10px;" class="flex align-center">-->
<!--              <el-icon style="font-size: 18px"><Avatar /></el-icon>-->
<!--              <span style="padding-left: 10px">请假人数</span>-->
<!--            </div>-->
<!--            <div style="font-size: 26px; color: #EF6363">2</div>-->
<!--          </div>-->
        </div>
        <div style="padding: 20px 0">选择必须参加活动的党员（没有要求不必选择）</div>
        <div class="person-container" style="border: 1px solid #E1E3E7; border-radius: 5px;min-height: 200px">
          <div class="flex" style="margin: 10px">
            <el-select v-model="meetingList"  filterable placeholder="请选择参会党员" multiple value-key="id" collapse-tags  clearable>
              <el-option v-for="(item,index) in activitySelectList.partyMemberList" :key="index" :label="item.pbUserName" :value="item"/>
            </el-select>

             <el-button  type="primary" style="margin-left: 12px" @click="addMeetingPerson">添加</el-button>
          </div>
          <div class="person-wrapper">

<!--            <div @click="delMeetingPerson(item)" class="item flex justify-content-space-between align-center" style="padding: 0 10px;margin-top: 10px;cursor: pointer" v-for="(item,index) in formData.userInfoList" :key="item.userId">-->
<!--              <div style="background-color: #E5E7EB;width:30px;height:30px;border-radius: 50%;color: #333333;font-size: 16px;" class="flex align-center justify-content-center">{{item.pbUserName.substring(0,1)}}</div>-->
<!--              <div style="color: black; padding: 0 10px;font-size: 16px;" class="flex-auto">{{item.pbUserName}}</div>-->
<!--              <img style="width: 20px;height: 20px;" class="flex align-center justify-content-center" src="../../../../assets/images/错误.png" alt="">-->
<!--            </div>-->

          </div>
        </div>
      </div>
    </div>

      <!------补充信息------>
      <div class="flex-auto" style="background-color: #ffffff;padding: 20px;margin-right: 10px;margin-top: 20px;">
        <div style="width: 100%;border-bottom: 1px solid #dedcdc;padding:0 0 10px 0;margin: 0 0 20px 0;font-size: 18px;color: #3d3838;font-weight: bolder">基本信息</div>
        <div style="margin-top: 20px">活动详情说明</div>
        <!-- 引入封装的富文本组件 -->
        <WangEditor ref="editorRef"
                    v-model="editorContent"
                    :height="200"
                    :toolbarConfig="toolbarConfig"
                    :editorConfig="editorConfig"
                    @change="onContentChange"
                    @created="onEditorCreated">
          <!-- 插槽：工具栏上方的自定义按钮 -->
          <!--          <template #toolbar-actions>-->
          <!--            <button type="button" class="action-btn" @click="insertCustomText">插入默认文本</button>-->
          <!--            <button type="button" class="action-btn" @click="getEditorText">获取纯文本</button>-->
          <!--            <button type="button" class="action-btn" @click="toggleDisable">{{ isDisabled ? '启用编辑' : '禁用编辑' }}</button>-->
          <!--            <button type="button" class="action-btn" @click="clearAllContent">清空内容</button>-->
          <!--          </template>-->

        </WangEditor>
      </div>
      <!------补充信息end------>

      <!------补充信息------>
      <div class="flex-auto" style="background-color: #ffffff;padding: 20px;margin-right: 10px;margin-top: 20px;">
        <div style="width: 100%;border-bottom: 1px solid #dedcdc;padding:0 0 10px 0;margin: 0 0 20px 0;font-size: 18px;color: #3d3838;font-weight: bolder">活动状态</div>
        <div style="margin-top: 20px">活动详情说明</div>
        <div class="status-container  flex justify-content-space-between" style="margin-top: 20px">
          <div class="status-item flex-auto flex  align-center justify-content-center"
               :style="index === activityStatus ? {border: '2px solid #F07278'} : ''"
               v-for="(item, index) in statusList" :key="index">
            <div class="icon-box ">
              <img :src="item.icon" style="width: 30px;height: 30px;display: block;margin: 0 auto"  alt="">
              <div class="status-desc" >{{item.desc}}</div>
            </div>
          </div>
        </div>
      </div>
      <!------补充信息end------>

    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer  flex justify-content-end" style="margin-right: 10px">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">{{ !!activityId ? '更新' : '提交' }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import { Search } from '@element-plus/icons-vue'
import WangEditor from './WangEditor.vue';
import {
  createActivity,
  getActivityType,
  getUserNameInfo,
  getActivityDetails,
  updateActivity
} from "@/api/life/relationship.js";
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});
defineExpose({
  loadActivityDetails
});
const activityId = ref(null);
const statusList = [
  { icon: new URL('../../../../assets/smart/筹备中.png', import.meta.url).href, desc: '筹备中'},
  { icon: new URL('../../../../assets/smart/进行中.png', import.meta.url).href, desc: '进行中'},
  { icon: new URL('../../../../assets/smart/已结束.png', import.meta.url).href, desc: '已结束'}
]
const emit = defineEmits(['update:modelValue', 'save']);
const dialogVisible = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  }
});
// 表单数据
const formData = ref({
  activityTypeId: '',  //类型id
  activityName: '', // 活动主题
  activityStartTime: '', // 开始时间
  activityEndTime: '',  // 结束时间
  activityAddress: '', // 活动地址
  activitySummary: '', // 内容
  userId:"", // 负责人id
  activitySupplement:"测试附件", // 附件信息
  userInfoList:[], //参会人员信息
  countUserNum:0, // 参会人员数量
});

const meetingList = ref([])

// 表单引用
const formRef = ref(null);

// 表单校验规则
const rules = {
  activityTypeId: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  activityName: [{ required: true, message: '请输入活动主题', trigger: 'blur' }],
  activityStartTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  activityEndTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  activityAddress: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  activitySummary: [{ required: true, message: '请输入活动内容', trigger: 'blur' }],
  userId: [{ required: true, message: '请选择活动责任人', trigger: 'change' }],
};

// 活动状态
const activityStatus = ref(0);

// 当前下拉列表
const activitySelectList = ref({
  partyMemberList:[], // 党员列表
  activityTypeList:[], // 活动类型列表
  statusList: [
    { icon: '', desc: '筹备中'},
    { icon: '', desc: '进行中'},
    { icon: '', desc: '已结束'}
  ]
});

// 监听开始时间和结束时间的变化
watch(
    [() => formData.value.activityStartTime, () => formData.value.activityEndTime],
    ([newStartTime, newEndTime]) => {
      if (newStartTime == 0 && newEndTime == 0){
         activityStatus.value = 0;
      }else {
        const now = new Date();
        const startDate = new Date(newStartTime);
        const endDate = new Date(newEndTime);
        if (now < startDate) {
          activityStatus.value = 0;
        } else if (now >= startDate && now <= endDate) {
          activityStatus.value = 1;
        } else if (now > endDate) {
          activityStatus.value = 2;
        }
      }
    },
    { immediate: true }
);

// 取消
const cancel = () => {
   onClose();
   dialogVisible.value = false;
};

// 关闭弹窗
const handleClose = () => {
  onClose();
  dialogVisible.value = false;
};

// 弹窗关闭时清空表单
const onClose = () => {
  // 重置表单数据
  formData.value = {
    activityTypeId: '',  //类型id
    activityName: '', // 活动主题
    activityStartTime: '', // 开始时间
    activityEndTime: '',  // 结束时间
    activityAddress: '', // 活动地址
    activitySummary: '', // 内容
    userId: "", // 负责人id
    activitySupplement:"", // 附件信息
    userInfoList:[], //参会人员信息
    countUserNum:0, // 参会人员数量
  };
  meetingList.value = [];
  // 清空活动ID，切换回新建模式
  activityId.value = null;
  // 清空表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 重置活动状态
  activityStatus.value = '';
  // 重置富文本编辑器内容
  editorContent.value = '<p>...</p>';
  if (editorRef.value) {
    editorRef.value.clear();
  }
};

// =============富文本编辑器===================
const editorContent = ref(''); // 编辑器内容（双向绑定）
const editorRef = ref(null); // 组件引用（用于调用内部方法）
const isDisabled = ref(false); // 禁用状态

// 工具栏配置
const toolbarConfig = reactive({});

// 2. 编辑器配置：控制编辑器本身的行为
const editorConfig = reactive({placeholder: '请输入内容...'});

// 编辑器创建完成时触发
const onEditorCreated = (editor) => {
  console.log('编辑器初始化完成', editor);
};

// 内容变化时触发
const onContentChange = (editor) => {
  console.log('当前内容：', editor.getHtml());
};

// 插入自定义文本
const insertCustomText = () => {
  editorRef.value?.insertText('这是插入的文本内容');
};

// 获取纯文本内容
const getEditorText = () => {
  const text = editorRef.value?.getText();
  alert('纯文本内容：\n' + text);
};

// 切换禁用/启用状态
const toggleDisable = () => {
  isDisabled.value = !isDisabled.value;
  if (isDisabled.value) {
    editorRef.value?.disable();
  } else {
    editorRef.value?.enable();
  }
};

// 清空内容
const clearAllContent = () => {
  editorRef.value?.clear();
};

// API 接口对接调试
const getActivityTypeList = async () => {
  let result = await getActivityType();
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200){
     activitySelectList.value.activityTypeList = data;
  }
}

// 获取参会人员
const getUserNameList = async () => {
  let result = await getUserNameInfo();
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200){
    activitySelectList.value.partyMemberList = data;
  }
}

// 去除参会人员
// const delMeetingPerson = (useId)=>{
//   console.log("userId",useId)
//   // formData.userInfoList = formData.userInfoList.filter(item => item.userId !== useId);
// }

// 参会人员
const addMeetingPerson = ()=>{
  try {
    const userIdList = meetingList.value.map(item => ({activityUserInfoId: item.id}));
    formData.value.userInfoList = JSON.parse(JSON.stringify(userIdList));
  }catch (e) {
    ElMessage.error("参会人员添加失败！")
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      addMeetingPerson()
      if (!!activityId.value == true){
           const reqData = {
            id: activityId.value,
            activityTypeId: formData.value.activityTypeId,
            activityName: formData.value.activityName,
            activityStartTime: formData.value.activityStartTime,
            activityEndTime: formData.value.activityEndTime,
            activityAddress: formData.value.activityAddress,
            activitySummary: formData.value.activitySummary,
            userId: formData.value.userId,
            activitySupplement: formData.value.activitySupplement,
            countUserNum: formData.value.countUserNum,
             createUserInfoList: formData.value.userInfoList,
            }
           let result = await updateActivity(reqData);
           let data = result.data.data;
           if (result.status == 200 && result.data.code == 200){
             ElMessage.success('活动修改成功!')
             dialogVisible.value = false;
             emit('save');
           }else {
             ElMessage.error('活动修改失败!');
           }
      }else {   // 新增
        let result = await createActivity(formData.value);
        let data = result.data.data;
        if (result.status == 200 && result.data.code == 200){
          ElMessage.success('活动创建成功!')
          emit('save');
          dialogVisible.value = false;
        }else {
          ElMessage.error('活动创建失败!');
        }
      }
    } else {
      console.log('表单校验失败')
    }
  })
}

// 获取活动详情
async function loadActivityDetails(id) {
  activityId.value = id;
  try {
    const response = await getActivityDetails({ guid: activityId.value });
    if (response.status == 200 && response.data.code == 200) {
      const activityData = response.data.data;
      // 填充表单数据
      formData.value = {
        ...formData.value,
        id: activityData.id,
        activityTypeId: activityData.activityTypeId,
        activityName: activityData.activityName,
        activityStartTime: activityData.activityStartTime,
        activityEndTime: activityData.activityEndTime,
        activityAddress: activityData.activityAddress,
        activitySummary: activityData.activitySummary,
        userId: activityData.userId,
        countUserNum: activityData.countUserNum,
        activitySupplement: activityData.activitySupplement,
        userInfoList: activityData.activityUserInfoList.map(item => ({
          id: item.cpcInfo.id,
          userId: item.cpcInfo.userId,
          pbUserName: item.cpcInfo.pbUserName,
          pbSex: item.cpcInfo.pbSex,
          pbStaffID: item.cpcInfo.pbStaffID,
          pbPhone: item.cpcInfo.pbPhone,
          pbDepartMentId: item.cpcInfo.pbDepartMentId,
          pbCommitteeId: item.cpcInfo.pbCommitteeId,
          pbPositionId: item.cpcInfo.pbPositionId,
          pbCreatorTime: item.cpcInfo.pbCreatorTime,
          pbStateId: item.cpcInfo.pbStateId,
          creationTime: item.cpcInfo.creationTime,
          creatorId: item.cpcInfo.creatorId,
          lastModifierId: item.cpcInfo.lastModifierId,
          lastModificationTime: item.cpcInfo.lastModificationTime,
          isDeleted: item.cpcInfo.isDeleted,
          pbDepartMent: item.cpcInfo.pbDepartMent,
          pbCommittee: item.cpcInfo.pbCommittee,
          pbPosition: item.cpcInfo.pbPosition,
          pbStateInfo: item.cpcInfo.pbStateInfo,
          extraProperties: item.cpcInfo.extraProperties,
          concurrencyStamp:item.cpcInfo.concurrencyStamp,
        })),
      };
      meetingList.value = formData.value.userInfoList
      // todo.....
      // 设置富文本内容
      // editorContent.value = activityData.activitySupplement || '';
      // 处理参会人员列表
      // if (activityData.userInfoList && Array.isArray(activityData.userInfoList)) {
      //   meetingList.value = activityData.userInfoList.map(user => {
      //     return activitySelectList.value.partyMemberList.find(member => member.userId === user.userId) || user;
      //   });
      // }
      ElMessage.success('活动信息加载成功');
    } else {
      ElMessage.error('获取活动详情失败');
    }
  } catch (error) {
    console.error('获取活动详情时出错:', error);
    ElMessage.error('加载活动信息时发生错误');
  }
}

getActivityTypeList();
getUserNameList();

</script>
<style scoped lang="scss">
.create-activity {
  padding: 20px;
  background: #f9f9f9;
}
.footer {
  text-align: right;
  margin-top: 30px;
}
.sign-in-list {
  background-color: #F9FAFB;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  overflow-y: auto;
  margin-top: 10px;
  .sign-item{
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    padding: 10px;
    border-radius: 8px;
    background: white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    font-size: 14px;
    .avatar{
      width: 32px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      background: #E5E7EB;
      border-radius: 50%;
      margin-right: 10px;
      font-size: 16px;
      color: #333333;
    }
    .status{
      color: #22C45E;
      font-size: 12px;
      padding: 2px 6px;

      border-radius: 4px;
    }
  }
}
.status-container{
  background-color: #FFFFFF;
  .status-item{
   padding: 20px 0;
    background-color: #ffffff;
    border-radius: 8px;
    border: 1px solid #E5E7EB;
    .status-desc{
      margin-top: 10px;
      color: #333333;
      font-weight: bolder;
      text-align: center;
    }
  }
  /* 中间项的样式 */
  .status-item:nth-child(2) {
    margin: 0 20px;
  }
}
</style>
